import { message } from "@bytedance/mona-ui"
import { generatedAiInit } from "../AIImage/generatedAiImages"
import { shuffleArray, isTransparentImage, upImageItemFunc, dealImageData, createTaskId } from "@contents/jinritemaiCopyGoods/copyDataFomate"

import { format } from './postDataInfo'
import db from "@tools/indexDB";
import { store } from "~store"
import moment from "moment";
let stop = false

export function fontStopConten() {
    stop = true
}

export async function formatFuncDeteail(data) {

    const { title, zhutu, sku, props, type = 1, cb = () => { } } = data
    let { userShopId = '' } = store.getState().jinritemaiShops
    const titleData = title.setConfigObj
    const zhutuData = zhutu.setConfigObj
    const skuData = sku.setConfigObj
    let getImageIndex = 0
    const copyMaxlen = props.copynum
    const ruleData = props.ruleData

    const taskId = createTaskId()
    stop = false

    const upCOnter = new setZhutuClass(zhutuData, JSON.parse(JSON.stringify(props)), cb, taskId)


    // 创建任务ID用于本地缓存任务进度
    const cheackImageContent = await upCOnter.cheackTipImage()
    if (!cheackImageContent) return
    /**
     * 一次性批量处理主图
     */
    // const setDataPromis = []
    // for (let i = 0; i < props.copynum; i++) {
    //     setDataPromis.push(upCOnter.runRefoData())
    // }

    // Promise.all(setDataPromis).then(res => {
    //     console.log('处理的图片结果', res)
    // })
    // return data

    console.log('开始开始123465789')
    cb && cb({
        status: 'start',
        msg: '开始进行',
        taskId,
        getImageIndex,
        copyMaxlen,
        progress: getImageIndex / copyMaxlen,
    })
    db.copyMaxProdecttask.add({
        taskId,
        shop_id: userShopId,
        list: [],
        createTime: moment().format('YYYY-MM-DD HH:mm:ss')
    }).then(() => {
        console.log('保存了任务的进度')
    })


    runIsCbFroFunc().then((res) => {

        cb && cb({
            status: res,
            msg: '处理完成',
            taskId,
            getImageIndex,
            copyMaxlen,
            progress: Number(((getImageIndex / copyMaxlen) * 100).toFixed(2)),
        })
    }).catch(Err => {
        console.log('错误', Err)
        cb && cb({
            status: 'err',
            msg: '处理错误',
            taskId,
            getImageIndex,
            copyMaxlen,
            progress: Number(((getImageIndex / copyMaxlen) * 100).toFixed(2)),
        })
    })

    async function runIsCbFroFunc() {
        if (stop) {
            return 'stop'
        }
        if (getImageIndex >= copyMaxlen) {
            return 'end'
        }

        // const res = await upCOnter.runRefoData()
        const setDataPromis = [upCOnter.runRefoData()]
        // console.log('setDataPromis', setDataPromis)

        const getConterll = await Promise.all(setDataPromis)
        getImageIndex++
        // console.log(`主图${getImageIndex}结果`, getConterll)
        // 开始上传商品

        // props.goodsDetellData.name = '2024新款A类加厚全棉磨毛四件套不掉毛100纯棉磨' //props.goodsDetellData.name.substring(8)
        // return
        const upcontentData = {
            setReForData: {
                deleailReFodata: props.goodsDetellData,
                picimageList: getConterll[0].map(item => {
                    return {
                        url: item
                    }
                }),
                prettify_info: (() => {
                    let deteilsData = props.goodsDetellData.description
                    let prettify_info = []
                    deteilsData.split('src="').forEach((res, index) => {
                        // console.log('ee', res.split("\" style=\""))
                        const spliteUrls = res.split('" style="')
                        spliteUrls.forEach((urls) => {
                            if (urls.includes("https") || urls.includes("http")) {
                                prettify_info.push({
                                    url: urls.replace('http:///"', '').replace('/"/', ''),

                                })
                            }
                        })
                    })
                    return prettify_info
                })(),
                start_sale_type: type // 审核通过后上架售卖时间配置:0-立即上架售卖 1-放入仓库
            }
        }
        const addProdectApiData = await format(upcontentData, ruleData)

        const addContentData = {
            olderLiter: props.goodsDetellData.product_id,
            title: upcontentData.setReForData.deleailReFodata.name,
            img: upcontentData.setReForData.picimageList,
            creted_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            data: addProdectApiData
        }
        const item = await db.copyMaxProdecttask.get(taskId);
        if (item) {
            item.list.push(addContentData);
            await db.copyMaxProdecttask.put(item).catch(err => {
                console.log('err....', err)
            })
        }
        // db.copyMaxProdecttask.where('taskId').anyOf([taskId]).modify({
        //     list: db.copyMaxProdecttask.get(taskId).list.concat(addContentData)
        // }).then(() => {
        //     console.log('保存了任务的进度')
        // }).catch(err => {
        //     console.log('errxxxxxxxx', err)
        // })


        cb && cb({
            status: 'start',
            msg: '进行中',
            taskId,
            getImageIndex,
            copyMaxlen,
            progress: Number(((getImageIndex / copyMaxlen) * 100).toFixed(2)),
        })
        return runIsCbFroFunc()
    }

}




class setZhutuClass {
    constructor(data, props, cb, taskId) {
        // this.cb = cb
        this.taskId = taskId
        this.copynum = props.copynum
        this.goodsDetellData = props.goodsDetellData
        this.goodsDetellDataCopy = JSON.parse(JSON.stringify(props.goodsDetellData))
        this.selectBiankuanIndex = -1
        this.runCouyerlist = []
        Object.keys(data).forEach(key => {
            this[key] = data[key]
        })
        // console.log('this', this)

    }
    async runRefoData() {

        this.initInfoData()
        if (this.setTypeStatus === 1) {
            const upData = await this.sheZhutu1()

            return upData
        }
        const upterData = await this.sheZhutu2()
        return upterData
    }
    initInfoData() {
        this.goodsDetellData = JSON.parse(JSON.stringify(this.goodsDetellDataCopy))
    }
    async cheackTipImage() {
        console.log('this.setTypeStatuswwwwwww', this.setTypeStatus)
        if (this.setTypeStatus === 1) {
            return await this.chearDatera(this.radioState).catch(err => {
                console.log('err', err)
                throw new Error(err)
            })
        }
        if (this.setTypeStatus === 2) {

            let selectConteFalse = false
            let contentter = []
            this.runCouyerlist = []
            for (let i = 1; i <= 8; i++) {

                if (this[`configType${i}Status`]) {
                    selectConteFalse = true
                    this.runCouyerlist.push(i + '')
                    contentter.push(this.chearDatera(i + '').catch(err => {
                        console.log('err', err)
                        throw new Error(err)
                    }))
                }
            }

            if (!selectConteFalse) {
                message.error('请先选择设置项目')
                throw new Error('请先选择设置项目')
            }
            return await Promise.all(contentter).catch(err => {
                console.log('errrr', err)
                throw new Error(err)
            })
        }

    }
    async sheZhutu1() {
        // console.log('单独设置', this.radioState)
        let addcntert = this.radioState
        if (this.setTypeStatus === 2) {
            const renmonum = Math.floor(Math.random() * this.runCouyerlist.length)
            addcntert = this.runCouyerlist[renmonum]
        }

        const cheackDataLenter = await this.chearDatera(addcntert).catch(err => {
            console.log('err', err)
            throw new Error(err)
        })

        if (!cheackDataLenter) return
        switch (addcntert) {
            case '1':
                return await this.setZhutuFunc1().catch(err => {
                    console.log('err', err)
                    return err
                })
            case '2':
                return await this.setZhutuFunc2().catch(err => {
                    return err
                })
            case '3':
                return await this.setZhutuFunc3().catch(err => {
                    return err
                })
            case '4':
                return await this.setZhutuFunc4().catch(err => {
                    return err
                })

            case '5':
                return await this.setZhutuFunc5().catch(err => {
                    return err
                })

            case '6':
                return await this.setZhutuFunc6().catch(err => {
                    return err
                })

            case '7':
                return await this.setZhutuFunc7().catch(err => {
                    return err
                })

            case '8':
                return await this.setZhutuFunc8().catch(err => {
                    return err
                })

            default:
                break
        }
    }
    sheZhutu2() {

        return this.sheZhutu1()
    }
    chearDatera(type) {
        return new Promise((resolve, reject) => {

            switch (type) {
                case '1':
                    if (!this.configType1.length) {

                        message.error('请选择AI替换位置')
                        return reject(false)
                    }
                    return resolve(true)

                case '2':
                    if (!this.configType2.length) {
                        message.error('请选择需要删除的图片位置')
                        return reject(false)
                    }
                    return resolve(true)
                case '3':
                    if (!this.configType3.upImageList.length) {
                        message.error('请上传需要添加的主图')
                        return reject(false)
                    }
                    return resolve(true)
                case '4':
                    if (!this.configType4.upImageList.length) {
                        message.error('请上传需要替换的主图')
                        return reject(false)
                    }
                    return resolve(true)
                case '8':
                    if (!this.configType8.selectBiankuanList.length) {
                        message.error('请选择边框')
                        return reject(false)
                    }
                    return resolve(true)
                default:
                    return resolve(true)
            }
        })


    }
    setZhutuFunc1() {


        return new Promise((resolve, reject) => {

            // 1 创建AI图片
            let { pic, product_id } = this.goodsDetellData
            let aiListImage = []
            const _this = this
            // resolve(pic)
            // return
            generatedAiInit({
                img_format: 1,
                product_id: product_id,
                url: pic[0],
                cb: function (data) {
                    // console.log('data', data)

                    // console.log('data', data.run_status)
                    // console.log('data', data.run_end_image_obj)
                    const { run_status } = data
                    if (run_status === 2) {
                        const getReunConterList = data.run_end_image_obj.filter(item => !item.extra_properties.pic_scale)
                        aiListImage.push(...getReunConterList)
                    }
                    if (run_status === 3) {
                        const getReunConterList = data.run_end_image_obj.filter(item => !item.extra_properties.pic_scale)
                        aiListImage.push(...getReunConterList)
                        data.run()
                    }

                    aiListImage = data.myseta(aiListImage)
                    // console.log('aiListImage', aiListImage)
                    if ((run_status === 2 || run_status === 3)) {
                        if (aiListImage.length < _this.configType1.length) {
                            data.run()
                            return
                        }
                        let indeAdd = 0
                        _this.configType1.forEach((item, index) => {
                            pic[item - 1] = aiListImage[index].img_url
                            indeAdd++
                        })

                        pic = pic.filter((iyter) => !!iyter).splice(0, 5)
                        resolve(pic)
                    }
                },
                setGetAiImageLodinStatus: (status) => {
                    console.log('status', status)
                },
                stopRun: false
            })
        })
        // 2 替换图片
    }
    setZhutuFunc2() {
        // console.log('删除主图', this.configType2)
        let { pic } = this.goodsDetellData
        let minLen = 3
        return new Promise((resolve, reject) => {
            if (pic.length <= minLen) {
                return resolve(pic)
            }
            const copylengter = JSON.parse(JSON.stringify(this.configType2))
            const deleteIndex = copylengter.splice(0, pic.length - minLen)
            pic = pic.filter((item, index) => {
                if (deleteIndex.includes((index + 1) + '')) {
                    return false
                }
                return true
            })
            resolve(pic)
        })
    }
    async setZhutuFunc3() {

        let { pic } = this.goodsDetellData
        const indexxser = this.configType3.type - 1
        // 随机选择一张插入到对应到位置
        const renderCOnter = Math.floor(Math.random() * this.configType3.upImageList.length)

        const userImage = this.configType3.upImageList[renderCOnter]

        const puterPic = pic.slice(0, indexxser).concat(userImage.url, pic.slice(indexxser)).filter((item => !!item)).splice(0, 5)  // .splice(0, 5)
        return puterPic

    }
    async setZhutuFunc4() {
        let { pic } = this.goodsDetellData
        const indexxser = this.configType4.type - 1
        // 随机选择一张插入到对应到位置
        const renderCOnter = Math.floor(Math.random() * this.configType4.upImageList.length)

        const userImage = this.configType4.upImageList[renderCOnter]

        pic[indexxser] = userImage.url
        //const puterPic = pic.slice(0, indexxser).concat(userImage.url, pic.slice(indexxser)).filter((item => !!item)).splice(0, 5)  // .splice(0, 5)
        return pic.filter((item => !!item)).splice(0, 5)
    }
    async setZhutuFunc5() {

        let { pic } = this.goodsDetellData
        if (this.configType5 == 1) {
            return pic
        }
        const pic1 = pic.splice(0, 1)
        pic.splice(this.configType5 - 1, 0, pic1[0])
        return pic
    }
    async setZhutuFunc6() {

        let { pic } = this.goodsDetellData

        // 将this.configType6-1 移动到pic的第一个位置
        if (this.configType6 == 1) {
            return pic
        }
        let splyer = this.configType6 - 1
        if (pic.length < splyer) {
            splyer = pic.length - 1
        }
        const pic1 = pic.splice(splyer, 1)
        pic.splice(0, 0, pic1[0])
        return pic
    }

    async setZhutuFunc7() {

        let { pic } = this.goodsDetellData
        if (this.configType7 == 1) {
            const zhutu1 = pic.splice(0, 1)
            const sjenr = shuffleArray(pic)
            return [...zhutu1, ...sjenr]
        }
        if (this.configType7 == 2) {
            return shuffleArray(pic)
        }

    }
    async setZhutuFunc8() {

        const { selectBiankuanList, selectBiankuanType, huangtuindex } = this.configType8
        let { pic } = this.goodsDetellData

        let getItemIndex = Math.floor(Math.random() * selectBiankuanList.length)
        if (selectBiankuanType == 2) {
            this.selectBiankuanIndex++
            if (!selectBiankuanList[this.selectBiankuanIndex]) {
                this.selectBiankuanIndex = 0
            }
            getItemIndex = this.selectBiankuanIndex
        }

        const item = selectBiankuanList[getItemIndex].url
        let getItemList = []
        let chnerIndexImage = 0
        if (huangtuindex === 6) {
            getItemList.push(...pic)
        } else {

            if (pic[huangtuindex - 1]) {
                chnerIndexImage = huangtuindex - 1

            } else {
                chnerIndexImage = pic.length - 1
                // getItemList.push(pic[pic.length - 1])
            }
            getItemList.push(pic[chnerIndexImage])
        }

        const upData = await setAndUpImageData(getItemList, item)

        if (huangtuindex === 6) {
            return pic.map((iteyr, index) => {
                if (!upData[index].code) {

                    iteyr = upData[index].data[0]
                }
                return iteyr
            })
        } else {
            pic[chnerIndexImage] = upData[0].data[0]
            return pic
        }

        async function setAndUpImageData(imageList, biankuan) {

            let putList = []

            const hetrit = await mergeImageCb(imageList, biankuan)
            async function mergeImageCb(list, img) {
                const setItem = list.splice(0, 1)

                if (!setItem[0]) {
                    return putList
                }
                // 合并图片
                const image1 = new Image()
                image1.src = setItem[0]
                image1.setAttribute("crossOrigin", "Anonymous")

                const image2 = new Image()
                image2.src = img
                image2.setAttribute("crossOrigin", "Anonymous")
                const promisLogdinAll = [new Promise((resolvea) => {
                    image1.onload = resolvea
                }), new Promise((resolvea) => {
                    image2.onload = resolvea
                })]
                let imagetype = 'image/jpeg'
                const ister = await isTransparentImage(setItem[0])
                if (ister) {
                    imagetype = 'image/png'
                }

                await Promise.all(promisLogdinAll)


                const canvas = document.createElement('canvas')
                const ctx = canvas.getContext('2d')
                const width = image1.width
                const height = image1.height
                canvas.width = width
                canvas.height = height

                ctx.drawImage(image1, 0, 0, width, height)
                ctx.drawImage(image2, 0, 0, width, height)


                let canvas2 = document.createElement("canvas")
                canvas2.width = canvas.width;
                canvas2.height = canvas.height;
                let ctx2 = canvas2.getContext("2d");
                let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                let imgData2 = dealImageData(imageData);
                ctx2.putImageData(imgData2, 0, 0);
                // orderData.mergeurl = canvas2.toDataURL(imagetype, 1)

                const base64 = canvas2.toDataURL(imagetype, 1)
                const upConternImga = await upImageItemFunc(base64).catch(err => {
                    console.log('err', err)
                    return err
                })

                putList.push(upConternImga)

                return mergeImageCb(list, img)
                // return base64
            }
            return hetrit

        }
    }
}
